// import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/components/Layout.vue'

export const constantRoutes = [
  {
    path: "/redirect",
    component: Layout,
    meta: { hidden: true },
    children: [
      {
        path: "/redirect/:path(.*)",
        component: () => import("@/views/redirect/index.vue"),
      }
    ]
  },
  {
    path: "/login",
    component: () => import("@/views/Login/index.vue"),
    meta: { hidden: true }
  },
  {
    path: '/',
    name: '',
    component: Layout,
    redirect: "/home",
    children: [
      {
        path: 'home',
        component: () => import("@/views/Home.vue"),
        name: 'Home',
        meta: {
          requiresAuth: true,  // 添加一个 meta 字段用于标识需要认证的路由
          title: "首页",
          icon: "el-icon-house",
          affix: true,
          keepAlive: true
        }
      },
      {
        path: "401",
        name: '401',
        component: () => import("@/views/401.vue"),
        meta: { hidden: true }
      },
      {
        path: "404",
        component: () => import("@/views/404.vue"),
        meta: { hidden: true }
      },
      {
        path: "profile",
        name: "Profile",
        component: () => import("@/views/Profile/index.vue"),
        meta: { title: "个人中心", icon: "user", hidden: true }
      }
    ]
  }
]

const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: constantRoutes,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // const isAuthenticated = !!sessionStorage.getItem('token')

  // if (to.matched.some(record => record.meta.requiresAuth)) {
  //   if (!isAuthenticated) {
  //     next({
  //       path: '/',
  //       query: { redirect: to.fullPath } // 保存重定向的目标路径
  //     })
  //   } else {
  //     next()
  //   }
  // } else {
  //   next() // 确保一定要调用 next()
  // }

  // 临时调试页面
  next()
})

export default router
